package com.uchedao.seller.util;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.uchedao.seller.R;
import com.uchedao.seller.inf.ICheckValueListener;


public class CheckTextEditValue {

	private TextView tv;
	private EditText et;
	private EditText et2;
	private ICheckValueListener listener;

	/**
	 * edit监听
	 * 
	 * @param viewGroup
	 * @param etResId
	 * @param text
	 * @param listener
	 */
	public CheckTextEditValue(ViewGroup viewGroup, int etResId, String text, ICheckValueListener listener) {
		this.listener = listener;
		et = (EditText) viewGroup.findViewById(etResId);
		et.addTextChangedListener(new TextStarWatcher(et));
		et.setText(text);
	}

	/**
	 * text edit监听
	 * 
	 * @param viewGroup
	 * @param tvResId
	 * @param etResId
	 * @param text
	 * @param listener
	 */
	public CheckTextEditValue(ViewGroup viewGroup, int tvResId, int etResId, String text, ICheckValueListener listener) {
		this.listener = listener;
		tv = (TextView) viewGroup.findViewById(tvResId);
		et = (EditText) viewGroup.findViewById(etResId);
		et.addTextChangedListener(new TextStarWatcher(et));
		et.setText(text);
	}

	/**
	 * text edit监听
	 * 
	 * @param viewGroup
	 * @param tvResId
	 * @param etResId
	 * @param text
	 * @param listener
	 */
	public CheckTextEditValue(ViewGroup viewGroup, int tvResId, int etResId, String text, int etResId2, String text2,
							  ICheckValueListener listener) {
		this.listener = listener;
		tv = (TextView) viewGroup.findViewById(tvResId);
		et = (EditText) viewGroup.findViewById(etResId);
		et.addTextChangedListener(new TextStarWatcher(et));
		et.setText(text);

		et2 = (EditText) viewGroup.findViewById(etResId2);
		et2.addTextChangedListener(new TextStarWatcher(et2));
		et2.setText(text2);
	}

	/**
	 * 监听有值时显示星号
	 * 
	 * @author "叶晋"
	 * 
	 */
	class TextStarWatcher implements TextWatcher {
		View view;

		public TextStarWatcher(View v) {
			view = v;
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {

		}

		@Override
		public void afterTextChanged(Editable s) {
			if (tv != null) {// 有textview时，设置星号是否显示
				if (et2 == null)
					setStar(tv, TextUtils.isEmpty(s));
				else
					setStar(tv, TextUtils.isEmpty(et.getText()) || TextUtils.isEmpty(et2.getText()));
			}
			if (listener != null)
				listener.getValue(view, s.toString().equals("") ? null : s.toString());
		}

		/**
		 * 设置是否显示星号
		 * 
		 * @param tv
		 * @param show
		 */
		void setStar(TextView tv, boolean show) {
			// tv.setCompoundDrawables(show ? DRAWABLE_STAR : DRAWABLE_STAR_NO,
			// null,
			// null, null);
			tv.setCompoundDrawablesWithIntrinsicBounds(show ? R.mipmap.read_star : R.mipmap.read_star_no, 0, 0, 0);
		}
	};

}
